package com.njcb.ams.web.controller.system;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.njcb.ams.factory.comm.DataBus;
import com.njcb.ams.pojo.dto.standard.Response;
import com.njcb.ams.repository.dao.CommCalendarDAO;
import com.njcb.ams.repository.dao.CommDataDicDAO;
import com.njcb.ams.repository.dao.mapper.CommCalendarMapper;
import com.njcb.ams.repository.entity.CommCalendar;
import com.njcb.ams.repository.entity.CommCalendarExample;
import com.njcb.ams.repository.entity.CommDataDic;
import com.njcb.ams.repository.entity.CommDataDicExample;
import com.njcb.ams.util.AmsJsonUtils;
import com.njcb.ams.pojo.dto.CalendarControllerDTO;
import com.njcb.ams.service.CalendarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 *
 * @author
 */
@Controller
@RequestMapping(value = "app/sysCalendar")
public class CalendarController {
    private static final Log log = LogFactory.getLog(CalendarController.class);

    @Autowired
    private CommCalendarMapper mapper;

    @Autowired
    private CommCalendarDAO dao;

    @Autowired
    private CalendarService calendarService;

    @Autowired
    private CommDataDicDAO commonDataDicDAO;




    /**
     * 查询下拉列表
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "initSel", method = RequestMethod.POST)
    @ResponseBody
    public String initSel(HttpServletRequest request, HttpServletResponse response) {
        CommDataDicExample example = new CommDataDicExample();
        CommDataDicExample.Criteria criteria = example.createCriteria();
        criteria.andDataTypeEqualTo("SysId");
        List<CommDataDic> list = commonDataDicDAO.selectByExample(example);
        List<CalendarControllerDTO> sysList = new ArrayList<>();

        for (int i=0;i<list.size();i++) {
            sysList.add(new CalendarControllerDTO(list.get(i).getDataNo(),list.get(i).getDataName()));

        }
//        sysList.add(new CalendarControllerDTO("CHN","CHN"));
//        sysList.add(new CalendarControllerDTO("USA","USA"));
//        sysList.add(new CalendarControllerDTO("BFIX","BFIX"));
        String outString = AmsJsonUtils.objectToJson(sysList);
        return outString;
    }


    /**
     * 初始化日历信息
     *
     * @return
     */
    @RequestMapping(value = "/initCalendar", method = RequestMethod.GET )
    @ResponseBody
    public Map<Object,Object> initCalendar(HttpServletRequest request, HttpServletResponse response) {
        String sysCalendarId = request.getParameter("sysCalendarId");
        String dataYear = request.getParameter("dataYear");
        calendarService.initCalendar(sysCalendarId, dataYear);
        Map<Object,Object> outDto = new HashMap<>();
        Map<String,String> data = inituseroper(DataBus.getUserName(),sysCalendarId,dataYear);
        outDto.put("user_conf_flag", data.get("user_conf_flag"));
        outDto.put("user_conf_no", data.get("user_conf_no"));
        return outDto;
    }
    //该步骤将用户修改的节假日还原， remar为空表示未生效
    private Map<String,String> inituseroper(String user_no,String sysCalendarId,String dataYear){
        Map<String,String> pDto = new HashMap<>();
        //当前用户编辑的数据置为反值
        pDto.put("data_year", dataYear);
        pDto.put("sys_id", sysCalendarId);
        pDto.put("oper_user", user_no);
        mapper.updateDateTypeByRemark(pDto);
        //将remar字段清空
        mapper.clearRemark(pDto);
        pDto.clear();
        //查询是否有冲突用户
        pDto.put("sys_id", sysCalendarId);
        pDto.put("data_year", dataYear);
        pDto.put("oper_user", user_no);
        List<CommCalendar> confList=mapper.checkConflits(pDto);
        Map<String,String> outDto = new HashMap<>();
        outDto.put("user_conf_flag", "0");
        if(confList.size()>0){
            outDto.put("user_conf_flag", "1");
            outDto.put("user_conf_no", confList.get(0).getRemark());
        }
        return outDto;
    }
    /**
     * 初始化节假日并标识
     *
     * @return
     */
    @RequestMapping(value = "initSunSatday",method = RequestMethod.POST)
    @ResponseBody
    public List<String> initSunSatday(HttpServletRequest request, HttpServletResponse response) {

        String year = request.getParameter("year");
        String sysId = request.getParameter("sysId");
        if (year.equals("")) {
            year = "";
        }
        if (sysId.equals("")) {
            sysId = "CHN";
        }
        Map<Object,Object> map = new HashMap<>();
        map.put("last_days", calendarService.getSuppDays(year));
        map.put("data_str", year);
        map.put("sys_id", sysId);
        List<String> days = dao.getSundayAndSatuday(map);
        return days;
    }

    /**
     * 查询节假日类型
     *
     * @return
     */
    @RequestMapping(value = "selectDataType",method = RequestMethod.POST)
    @ResponseBody
    public String selectDataType(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> qDto = new HashMap<>();
        String dataStr = request.getParameter("dataStr");
        String year = dataStr.split("-")[0];
        String month = dataStr.split("-")[1];
        String day = dataStr.split("-")[2];
        if (month.length() == 1) {
            month = "0" + month;
        }

        if (day.length() == 1) {
            day = "0" + day;
        }

        String dataStr2 = year + month + day;
        String sysId = request.getParameter("sysId");
        qDto.put("data_str", dataStr2);
        qDto.put("sys_id", sysId);
        String s = mapper.selectDataType(qDto);

        return s;
    }

    /**
     * 新增保存
     *
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    @ResponseBody
    public Response add(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> qDto = new HashMap<>();
        if (log.isDebugEnabled()) {
            log.debug(qDto);
        }
        String sysId = request.getParameter("sysId");
        String dataType = request.getParameter("dataType");
        String dataStr = request.getParameter("dataStr");
        String year = dataStr.split("-")[0];
        String month = dataStr.split("-")[1];
        String day = dataStr.split("-")[2];
        if (month.length() == 1) {
            month = "0" + month;
        }

        if (day.length() == 1) {
            day = "0" + day;
        }
        String dataStr2 = year + month + day;

        String date = dataStr.substring(4);
//		if (date.length() == 2) {
//			date = "0" + date.substring(0,1) + "0" + date.substring(1,2);
//			dataStr += dataStr.substring(0,4) + date;
//		} else if (date.length() == 3) {
////			if ()
//		}
        qDto.put("sys_id", sysId);
        qDto.put("data_type", dataType);
        qDto.put("data_str", dataStr2);
        qDto.put("oper_user", DataBus.getUserName());
        // qDto.put("end_date",endDate );
        HashMap<String,String> outDto = new HashMap<>();
        String msg ="";
        try {
            //	update(qDto);
            mapper.addTypeCalendar(qDto);
            msg = "操作完成，修改成功";
            return Response.buildSucc(msg);
        } catch (Exception e) {
            msg = "修改失败!原因:" + e.getMessage();
            log.error("修改失败!", e);
            return Response.buildFail(msg);
        }

    }
    /**
     * 新增保存
     *
     * @return
     */
    @RequestMapping(value = "saveall", method = RequestMethod.POST)
    @ResponseBody
    public Response saveall(HttpServletRequest request, HttpServletResponse response) {
        Map<String,String> qDto = new HashMap<>();
        if (log.isDebugEnabled()) {
            log.debug(qDto);
        }
        String sysId = request.getParameter("sysId");
        String dataYear = request.getParameter("year");
        qDto.put("sys_id", sysId);
        qDto.put("data_year", dataYear);
        qDto.put("oper_user", DataBus.getUserName());
        mapper.upuserCalendar(qDto);
        // qDto.put("end_date",endDate );
        return Response.buildSucc("保存成功");
    }
	/**
	 * 统计节假日天数
	 *
	 * @return
	 */
	@RequestMapping(value = "sumdays", method = RequestMethod.POST)
    @ResponseBody
	public Map<String,String> sumdays(HttpServletRequest request, HttpServletResponse response) {
		Map<String,String> qDto = new HashMap<>();
		if (log.isDebugEnabled()) {
			log.debug(qDto);
		}
		String sysId = request.getParameter("sysId");
		String dataYear = request.getParameter("year");
		Map<String,String> pDto = new HashMap<>();
		pDto.put("sys_id", sysId);
		pDto.put("data_year", dataYear);
		pDto.put("data_type", "1");
        CommCalendarExample example = new CommCalendarExample();
        CommCalendarExample.Criteria criteria = example.createCriteria();
        criteria.andDataYearEqualTo(dataYear);
        criteria.andSysIdEqualTo(sysId);
        criteria.andDataTypeEqualTo("1");
        List<CommCalendar> list = mapper.selectByExample(example);
		Map<String,String> outDto = new HashMap<>();
		outDto.put("appcode","1");
		outDto.put("appmsg","假期类型["+sysId+"]["+dataYear+"]年节假日为["+list.size()+"]天");
        return outDto;
	}

}